package org.example.day04;

/**
 * 第二章节2.2.5:synchronized 代码块间的同步性
 * 调用serviceMethodA()和serviceMethodB()方法中的this都是m5对象，线程A先进入methodA未释放锁时，线程B进不去methodB方法。
 */
public class MyThread5 {
    public void serviceMethodA(){
        try {
            synchronized (this){
                System.out.println("A beginTime = " + System.currentTimeMillis());
                Thread.sleep(2000);
                System.out.println("A endTime = " + System.currentTimeMillis());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void serviceMethodB(){
        synchronized (this){
            System.out.println("B beginTime = " + System.currentTimeMillis());
            System.out.println("B endTime = " + System.currentTimeMillis());
        }
    }

    public static void main(String[] args) {
        MyThread5 m5 = new MyThread5();
        Thread5A ta = new Thread5A(m5);
        ta.setName("A");
        ta.start();
        Thread5B tb = new Thread5B(m5);
        tb.setName("B");
        tb.start();
    }
}

class Thread5A extends Thread{
    private MyThread5 m5;

    public Thread5A(MyThread5 m5) {
        this.m5 = m5;
    }

    @Override
    public void run() {
        m5.serviceMethodA();
    }
}
class Thread5B extends Thread{
    private MyThread5 m5;
    public Thread5B(MyThread5 m5) {
        this.m5 = m5;
    }

    @Override
    public void run() {
        m5.serviceMethodB();
    }
}


